package com.voicechat.firstmet.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.LoginService;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: LoginActivity
 * @Description: 登录页面
 * @Author: ljp
 * @CreateDate: 2018/8/28 17:44
 * @Version: 1.0
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.linear_choose)
    LinearLayout linearChoose;
    @BindView(R.id.et_phone_num)
    EditText etPhoneNum;
    @BindView(R.id.image_delete)
    ImageView imageDelete;
    @BindView(R.id.login_sure)
    TextView loginSure;
    @BindView(R.id.image_share_wx)
    ImageView imageShareWx;
    @BindView(R.id.image_share_qq)
    ImageView imageShareQq;
    @BindView(R.id.image_share_wb)
    ImageView imageShareWb;
    @BindView(R.id.tv_terms)
    TextView tvTerms;
    @BindView(R.id.tv_user)
    TextView tvUser;
    private String TAG = "LoginActivity";
    private static final String[] PERMISSIONS_CONTACT = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA,};
    private static final int REQUEST_CONTACTS = 1000;
    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        //Log.i(TAG, "initLayout: -------"+ PhoneUtils.getDeviceInfo(context));
        //手机号码输入监听
        //List<EmojiEntity> emojiEntities = JsonParseUtil.parseEmojiList(FileUtils.readAssetsFile(this, "EmojiList.json"));
      /*  try {
           // String encode = URLEncoder.encode(String.valueOf(emojiEntities.get(0).getUnicode()), "UTF-8");
            //Log.i(TAG, "setPasswore: ----emojiEntities----"+encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        loginSure.setClickable(false);
        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phoneNum = s.toString().trim();
                if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() != 0) {
                    imageDelete.setVisibility(View.VISIBLE);
                    if (phoneNum.length() == 11) {
                        loginSure.setClickable(true);
                        loginSure.setBackgroundResource(R.drawable.login_btn);
                    } else {
                        loginSure.setClickable(false);
                        loginSure.setBackgroundResource(R.drawable.login_btn_2);
                    }
                } else {
                    imageDelete.setVisibility(View.GONE);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvTerms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, WebPageActivity.class);
                intent.putExtra("url", "file:///android_asset/web/privacy.html");
                intent.putExtra("title", "用户隐私协议");
                startActivity(intent);
            }
        });
        tvUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, WebPageActivity.class);
                intent.putExtra("url", "file:///android_asset/web/user.html");
                intent.putExtra("title", "用户协议");
                startActivity(intent);
            }
        });
        imageDelete.setOnClickListener(this);
        loginSure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_delete:
                etPhoneNum.setText("");
                break;
            case R.id.login_sure:
                loginSure.setEnabled(false);
                phoneNumjudge();
                break;
        }

    }

    /**
     * @param
     * @description 确定按钮事件处理（手机号码判断，进行网络请求）
     * @date: 2018/8/30 9:40
     * @author: ljp
     */
    private void phoneNumjudge() {
        String phoneNumber = etPhoneNum.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)) {
            toast_MakeText("请输入手机号码");
        } else if (!Utils.isMobileNO(phoneNumber)) {
            toast_MakeText("手机号码格式不正确，请重新输入");
        } else {
            //此时网络请求
            LoginService.registerJud(phoneNumber).subscribe(result -> {
                Log.i(TAG, "phoneNumjudge: -----" + result.toString());
                //验证码发送成，跳到输入验证码页面
                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS || result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_OVERTIME) {
                    Intent intent = new Intent(this, GetCodeActivity.class);
                    intent.putExtra("mobile", phoneNumber);
                    intent.putExtra("flag", "0");
                    intent.putExtra("code", result.getCode());
                    startActivity(intent);
                } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_USE) {   //已经注册用户，直接跳到密码登录页面
                    Log.i(TAG, "phoneNumjudge: ------------------");
                    Intent intent = new Intent(this, LoginPassWordActivity.class);
                    intent.putExtra("mobile", phoneNumber);
                    intent.putExtra("flag", "0");
                    startActivity(intent);
                } else {
                    toast_MakeText("验证码超时");
                }
            }, throwable -> {
                Log.i(TAG, "phoneNumjudge: -----" + throwable.toString());
            });
            //startActivity(new Intent(this,LoginPassWordActivity.class));
        }
        loginSure.setEnabled(true);
    }
    @Override
    protected void onStart() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            requestContactsPermissions();
        }
        super.onStart();
    }
    /**
     * 权限判断
     */
    private void requestContactsPermissions() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                || ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)
                ) {
            // Log.i(TAG, "requestContactsPermissions: -----" + "--------------");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("隐隐申请读取位置权限");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat
                            .requestPermissions(activity, PERMISSIONS_CONTACT,
                                    REQUEST_CONTACTS);
                    dialog.dismiss();//此处换成删除，这是一个结束返回
                }
            });
            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.create().show();
        } else {
            ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        }
    }

}